package c.x.jy.service.service.impl;

import c.x.jy.common.exception.RRException;
import c.x.jy.common.utils.GetClassinfo;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.Query;
import c.x.jy.common.utils.SysUtils;
import c.x.jy.dao.dao.OrderDao;
import c.x.jy.dao.dto.OrderEntityDto;
import c.x.jy.dao.dto.ServiceEntityDto;
import c.x.jy.dao.entity.*;
import c.x.jy.dao.model.OrderForm;
import c.x.jy.service.config.BusinessConfigService;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.redis.RedisConstant;
import c.x.jy.service.service.*;
import c.x.jy.service.utils.MemberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberService customerService;
    @Autowired
    private Environment env;
    @Autowired
    private OrderBillService orderBillService;
    @Autowired
    private OrderItemsService orderItemsService;
    @Autowired
    private c.x.jy.service.service.TeacherServiceService teacherServiceService;
    @Autowired
    private  BirthService birthService;
    @Autowired
    private TeacherConfigService tacherConfigService;

    @Autowired
    private  QuicktestService quicktestService;
    @Autowired
    private   RechargeService rechargeService;

    @Autowired
    private Cache redisUtils;

    @Autowired
    private BusinessConfigService businessConfigService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private ServiceService serviceService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        	QueryWrapper<OrderEntity> query= 	 new QueryWrapper<OrderEntity>() ;
    	if(params.get("searchKey")!=null&&params.get("searchValue")!=null&&!StringUtils.isEmpty(params.get("searchKey").toString())&&!StringUtils.isEmpty(params.get("searchValue").toString()))
    	    query.eq(  params.get("searchKey").toString(), params.get("searchValue"));


        if(params.get("businessId")!=null) 	query.eq("business_id", params.get("businessId"));
        if(params.get("memberId")!=null)query.eq("member_id", params.get("memberId"));
        if(params.get("teacherId")!=null)query.eq("teacher_id", params.get("teacherId"));
        if(params.get("status")!=null)query.eq("status", params.get("status"));
        if(params.get("serviceType")!=null)query.eq("service_type", params.get("serviceType"));
//            IPage<OrderEntity> page = this.page(  new Query<OrderEntity>().getPage(params),  query  );
        IPage<OrderEntityDto> page =   this.getBaseMapper().querypage(new Query<OrderEntity>().getPage(params),  query);

        return new PageUtils(page);
    }
    @Transactional
    @Override
    public OrderEntity saveNewOrder(OrderForm orderfrm) {
        MemberEntity curUser = memberService.getCurrUser();
        if(orderfrm.getServiceType().equals(1)){
            if(curUser.getMemberLevel().equals(0)){
                throw new RRException("您还不是会员，请先开通VIP会员再购买");
            }
        }

        if(orderfrm.getServiceType()==null){
            throw new RRException("类型不能为空！");
        }
        if(orderfrm.getTeacherId()==null&&!OrderForm.orderType.quick.getType().equals(orderfrm.getServiceType())&&!OrderForm.orderType.member_cert.getType().equals(orderfrm.getServiceType())&&!OrderForm.orderType.recharge.getType().equals(orderfrm.getServiceType())){
            throw new RRException("大师ID不能为空！");
        }
        if( orderfrm.getItemList()==null|| orderfrm.getItemList().isEmpty()){
            throw new RRException("服务项目不能为空！");
        }


        if(orderfrm.getServiceType()!=OrderForm.orderType.ask.getType()){
            orderfrm.getItemList().forEach((d)->{
                if( d.getItemId()==null)
                    throw new RRException("服务ID不能为空！");
                if(!d.getItemType().equals(orderfrm.getServiceType()))
                    throw new RRException("服务类型不匹配！");
            });

         //   throw new RRException("服务ID不能为空！");
        }else  if(orderfrm.getServiceType()==OrderForm.orderType.ask.getType()){
            orderfrm.getItemList().forEach((d)->{
                if( d.getBirthId()==null||d.getItemName()==null||StringUtils.isEmpty(d.getItemName())||StringUtils.isEmpty(d.getDescription()))
                    throw new RRException("提问参数不能为空！");
            });
        }


        return createNewOrder(orderfrm);
    }

    @Override
    public void removePay(String orderNo) {

        redisUtils.remove(RedisConstant.REDISLOCK_KEY,
                orderNo + ":" + MemberUtil.get().getOpenid());

    }

    private OrderEntity createNewOrder(OrderForm ofrm){
        OrderEntity order=new OrderEntity();
        order.setBusinessId(customerService.getCurrUser().getBusinessId());
        order.setMemberId(customerService.getCurrUser().getId());
        order.setCreateDate(new Date());
        order.setOrderNo(SysUtils.generateSnowflake(Integer.valueOf(env.getProperty("xuanzhu.Snowflake.workId")), 	Integer.valueOf(env.getProperty("xuanzhu.Snowflake.dataId"))).toString());
        order.setServiceType(ofrm.getServiceType());
        order.setStatus(0);
        if(ofrm.getServiceType()==2)ofrm.setTeacherId(-2l);
        else if(ofrm.getServiceType()==4)ofrm.setTeacherId(-4l);
        else if(ofrm.getServiceType()==5)ofrm.setTeacherId(-5l);
        order.setTeacherId(ofrm.getTeacherId()==null?-1l:ofrm.getTeacherId());
        this.baseMapper.insert(order);

        OrderBillEntity orderBill=new OrderBillEntity();
        orderBill.setBusinessId(customerService.getCurrUser().getBusinessId());

        orderBill.setOrderNo(order.getOrderNo());
        orderBill.setCreateDate(new Date());
        orderBill.setMemberId(customerService.getCurrUser().getId());
        orderBill.setPayType(0);
        orderBill.setStatus(0);
        //orderBill.setTransNumber();
      //  orderBill.setActualPrice(BigDecimal.ZERO);
        orderBill.setOrderId(order.getId());
        orderBill.getOriginalPrice();
        orderBill.setDiscountPrice(BigDecimal.ZERO);
//         //券
//        orderBill.setCouponDesc();
//        orderBill.setCouponId();
//        orderBill.setCouponPrice();
//        orderBill.setCouponTransId();
//
//       //积分
//        orderBill.setIntegralCount();
//        orderBill.setIntegralPrice();
//        orderBill.setIntegralTransId();
//        //会员卡
//        orderBill.setVipId();
//        orderBill.setVipPrice();
//        orderBill.setVipTransId();
      orderBill.setCommont(OrderForm.orderType.getName(ofrm.getServiceType())+":");
        
        List<OrderItemsEntity> itemlist=new ArrayList<>();
        orderBill.setItemlist(itemlist);
        ofrm.getItemList().forEach((item)->{
            OrderItemsEntity orderitem=new OrderItemsEntity();
            orderitem.setCreateDate(new Date());
            orderitem.setItemType(item.getItemType());
            orderitem.setOrderId(order.getId());
            orderitem.setQuantity(1);
            if(item.getBirthId()!=null|| birthService.count(new QueryWrapper<BirthEntity>().lambda().eq(BirthEntity::getId,item.getBirthId()))>0){
                orderitem.setBirthId(item.getBirthId());
            }

          if(item.getItemType().equals(OrderForm.orderType.consult.getType())){
		           ServiceEntityDto sevice=   teacherServiceService.selectServiceInfoById(item.getItemId());
		           if(sevice==null)throw new RRException("未找到服务项目!");
             // TeacherConfigEntity cofnig= tacherConfigService.getById(ofrm.getTeacherId());
            //  if(cofnig==null||cofnig.getAskPrice()==null )throw new RRException("当前大师未配置!");

                  orderitem.setItemId(item.getItemId());
	              orderitem.setDescription(sevice.getDescription());
	              orderitem.setItemName(sevice.getItemName());

                    orderitem.setImages(sevice.getMiniImage());
	              orderitem.setDiscountPrice(sevice.getDiscountPrice());
	              orderitem.setOriginalPrice(sevice.getOriginalPrice());
          }else if(item.getItemType().equals(OrderForm.orderType.quick.getType())){
//	              if(orderitem.getBirthId()==null)throw new RRException("生辰信息不能为空!");
	            //  TeacherConfigEntity cofnig= tacherConfigService.getById(ofrm.getTeacherId());
	          //    if(cofnig==null||cofnig.getJoinQuickAsk()==null&&!cofnig.getJoinQuickAsk().equals(1))throw new RRException("当前大师当前未加入闪测!");
	               QuicktestEntity quick=    quicktestService.getById(item.getItemId());
	              if(quick==null)throw new RRException("未找到服务项目!");
	              orderitem.setItemId(item.getItemId());
	              orderitem.setDescription(quick.getDescription());
	              orderitem.setItemName(quick.getTitle());
                    orderitem.setImages(quick.getImage());
	              orderitem.setDiscountPrice(quick.getDiscountPrice());
	              orderitem.setOriginalPrice(quick.getOriginalPrice());
            }else if(item.getItemType().equals(OrderForm.orderType.ask.getType())) {
	              if (orderitem.getBirthId() == null) throw new RRException("生辰信息不能为空!");
	              orderitem.setOpenQuestions(item.getOpenQuestions() == null ? 0 : item.getOpenQuestions());
	              orderitem.setImages(item.getImage());
	              orderitem.setDescription(item.getDescription());
	              orderitem.setItemName(item.getItemName());
	              TeacherConfigEntity cofnig = tacherConfigService.getByTeacherId(ofrm.getTeacherId());
	              if (cofnig == null||cofnig.getAskPrice()==null ) throw new RRException("大师当前未配置!");
	              orderitem.setDiscountPrice(cofnig.getAskPrice());
	              orderitem.setOriginalPrice(cofnig.getAskPrice());
          }else if(item.getItemType().equals(OrderForm.orderType.recharge.getType())){
	              RechargeEntity rearge=   rechargeService.getById(item.getItemId());
              if (rearge == null) throw new RRException("充值清单未配置!");
	              orderitem.setItemId(rearge.getId());
	              orderitem.setDescription(rearge.getName());
	              orderitem.setItemName(rearge.getName());
	              orderitem.setDiscountPrice(rearge.getDiscountPrice());
	              orderitem.setOriginalPrice(rearge.getOriginalPrice());
            }else if(item.getItemType().equals(OrderForm.orderType.member_cert.getType())){
              String price = businessConfigService.getBusinessConfigValue(null,"VIP_CERT_PRICE");
              if (price == null) throw new RRException("会员开通价格未配置!");

              orderitem.setDescription("会员开通");
              orderitem.setItemName("会员开通" );
              orderitem.setDiscountPrice(new BigDecimal(price));
              orderitem.setOriginalPrice(new BigDecimal(price));
          }
          
          orderBill.setCommont(orderBill.getCommont()+orderitem.getItemName());
     
            itemlist.add(orderitem);
            orderItemsService.save(orderitem);
        });
        orderBill.getDiscountPrice();
        orderBillService.save(orderBill);
        order.setItemlist(itemlist);
        order.setOrderBill(orderBill);
 
        return order;

    }
	@Override
	public OrderEntity selectOrderByNo(String orderNo) {
		// TODO Auto-generated method stub
		return       this.baseMapper.selectOrderByNo(orderNo);
	}

    @Override
    public PageUtils newquickask(Map<String, Object> params) {
        QueryWrapper<OrderEntity> query= 	 new QueryWrapper<OrderEntity>() ;
//        if(params.get("searchKey")!=null&&params.get("searchValue")!=null&&!StringUtils.isEmpty(params.get("searchKey").toString())&&!StringUtils.isEmpty(params.get("searchValue").toString()))
//            query.eq(  params.get("searchKey").toString(), params.get("searchValue"));
        //query.lambda().eq(OrderEntity::getStatus, 4).or().eq(OrderEntity::getStatus,0);
        query.lambda().eq(OrderEntity::getStatus, 4);
        query.lambda().eq(OrderEntity::getServiceType, 2);
//            IPage<OrderEntity> page = this.page(  new Query<OrderEntity>().getPage(params),  query  );
        IPage<OrderEntityDto> page =   this.getBaseMapper().querypage(new Query<OrderEntity>().getPage(params),  query);

        return new PageUtils(page);
    }


    @Override
    public OrderEntityDto infodto(Long id) {

        OrderEntity orderEntityDto = this.getBaseMapper().selectById(id);
        OrderEntityDto dto=new OrderEntityDto();
        GetClassinfo.ObjectChangeToObject(orderEntityDto,dto);
        return dto;
    }
	@Override
	public OrderEntity selectOrderBYIdForUpdate(Long orderId) {
	    if(orderId==null)return null;
		return this.baseMapper.selectOrderBYIdForUpdate(orderId);
	}


}
